from rest_framework import serializers
from .models import City, DataCenter, Host, HostCredential, HostStatistics


class CitySerializer(serializers.ModelSerializer):
    """城市序列化器"""
    class Meta:
        model = City
        fields = ['id', 'name', 'code', 'created_at', 'updated_at']
        read_only_fields = ['id', 'created_at', 'updated_at']


class DataCenterSerializer(serializers.ModelSerializer):
    """机房序列化器"""
    city_name = serializers.CharField(source='city.name', read_only=True)
    
    class Meta:
        model = DataCenter
        fields = ['id', 'name', 'code', 'city', 'city_name', 'address', 
                 'contact_person', 'contact_phone', 'created_at', 'updated_at']
        read_only_fields = ['id', 'created_at', 'updated_at']


class HostSerializer(serializers.ModelSerializer):
    """主机序列化器"""
    datacenter_name = serializers.CharField(source='datacenter.name', read_only=True)
    city_name = serializers.CharField(source='datacenter.city.name', read_only=True)
    
    class Meta:
        model = Host
        fields = ['id', 'hostname', 'ip_address', 'datacenter', 'datacenter_name', 
                 'city_name', 'status', 'os_type', 'cpu_cores', 'memory_gb', 
                 'disk_gb', 'ssh_port', 'description', 'last_ping_time', 
                 'last_ping_result', 'created_at', 'updated_at']
        read_only_fields = ['id', 'last_ping_time', 'last_ping_result', 'created_at', 'updated_at']


class HostCredentialSerializer(serializers.ModelSerializer):
    """主机凭证序列化器"""
    password = serializers.CharField(write_only=True, help_text="明文密码，将自动加密存储")
    
    class Meta:
        model = HostCredential
        fields = ['id', 'host', 'username', 'password', 'password_updated_at', 'created_at']
        read_only_fields = ['id', 'password_updated_at', 'created_at']
        extra_kwargs = {
            'encrypted_password': {'write_only': True}
        }
    
    def create(self, validated_data):
        password = validated_data.pop('password')
        credential = HostCredential.objects.create(**validated_data)
        credential.set_password(password)
        credential.save()
        return credential
    
    def update(self, instance, validated_data):
        if 'password' in validated_data:
            password = validated_data.pop('password')
            instance.set_password(password)
        
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        return instance


class HostStatisticsSerializer(serializers.ModelSerializer):
    """主机统计序列化器"""
    city_name = serializers.CharField(source='city.name', read_only=True)
    datacenter_name = serializers.CharField(source='datacenter.name', read_only=True)
    
    class Meta:
        model = HostStatistics
        fields = ['id', 'city', 'city_name', 'datacenter', 'datacenter_name',
                 'total_hosts', 'online_hosts', 'offline_hosts', 'maintenance_hosts',
                 'statistics_date', 'created_at']
        read_only_fields = ['id', 'created_at']


class PingResultSerializer(serializers.Serializer):
    """Ping结果序列化器"""
    host_id = serializers.IntegerField()
    hostname = serializers.CharField()
    ip_address = serializers.IPAddressField()
    is_reachable = serializers.BooleanField()
    response_time = serializers.FloatField(allow_null=True)
    ping_time = serializers.DateTimeField()
    error_message = serializers.CharField(allow_null=True, allow_blank=True)
